<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Sgdzz\OrderDetailLog;
use App\Models\Sgdzz\Issue;
use App\Models\Sgdzz\PayLog;
use App\GameZghpt;
use App\User;
use App\UserCoinLog;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Jobs\SendWechatMessage;

class SgdzzFinishIssue extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sgdzz:finishIssue';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '水果大作战开奖';
    
    //奖励层级
    private $reward_count = 2;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        try {
            //查询正在进行的期号
            $currentIssue = Issue::getRunningIssue();
            
            $statusRunning  = Issue::STATUS_RUNNING;
            $statusOpening  = Issue::STATUS_OPENING;
            $statusFinished = Issue::STATUS_FINISHED;

            if (empty($currentIssue['id']) || $currentIssue['openAfter'] > -2) {  //没有进行中 或 还没到时间
                return false;
            } else {    //可以开奖
                try {
                    echo "Issue: {$currentIssue['id']} begin\n";
                    echo "openAfter: {$currentIssue['openAfter']}\n";
                    echo "Time: " . date('Y-m-d H:i:s') . "\n";
                    DB::beginTransaction();
                    //设置为待开奖
                    $res = Issue::where('id', $currentIssue['id'])->where('status', $statusRunning)->update(['status' => $statusOpening]);
                    if (empty($res)) {
                        throw new \Exception("无法更新为待开奖状态");
                    }
                    //计算开奖
                    $orderDetail = OrderDetailLog::getOrderDetail($currentIssue['id']);

                    //默认开奖类型
                    $typeArr = [Issue::TYPE_PINEAPPLE, Issue::TYPE_BANANA, Issue::TYPE_APPLE];
                    shuffle($typeArr);
                    $winType = array_pop($typeArr);

                    //按类型汇总
                    $orderDetailSumByType = OrderDetailLog::getOrderDetailSumByType($orderDetail);
                    
                    //排序，小的在上面
                    //asort($orderDetailSumByType);     //最小购买的类型在上面
                    //取购买量最小的开奖
                    //foreach ($orderDetailSumByType as $type => $gold) {
                    //    $winType = $type;
                    //    break;
                    //}
                    $winType = array_rand($orderDetailSumByType, 1);
                    echo "winType: {$winType} \n";

                    //设置开奖结果
                    $issueItem = Issue::where('id', $currentIssue['id'])->where('status', $statusOpening)->first();
                    if (!empty($issueItem->id)) {   //待开奖
                        $res = Issue::where('id', $currentIssue['id'])->where('status', $statusOpening)->update(['status' => $statusFinished, 'win_type' => $winType,]);
                        if (empty($res)) {
                            throw new \Exception("无法更新为已开奖状态");
                        } else {
                            //记录订单详情的中奖标记
                            $rows = OrderDetailLog::updateWinType($currentIssue['id'], $winType);
                            echo "win rows: {$rows} \n";
                            
                            $now = time();
                            //开奖成功，发放奖励
                            $orderDetailSumByTypeUserId = OrderDetailLog::getOrderDetailSumByTypeUserId($orderDetail);
                            if (isset($orderDetailSumByTypeUserId[ $winType ])) {
                                echo "中奖详情：\n";
                                echo print_r($orderDetailSumByTypeUserId[ $winType ], true) . "\n";
                                foreach ($orderDetailSumByTypeUserId[ $winType ] as $userId => $gold) {
                                    //奖励金额
                                    $awardGold = $gold * config('sgdzz.award_times');

                                    //获取新的用户信息
                                    $user = User::find($userId);
                                    //记录奖励
                                    $payLogModel              = new PayLog();
                                    $payLogModel->user_id     = $userId;
                                    $payLogModel->from_XYB    = $user->XYB;
                                    $payLogModel->add_XYB     = $awardGold;
                                    $payLogModel->to_XYB      = $user->XYB + $gold;
                                    $payLogModel->issue       = $currentIssue['id'];
                                    $payLogModel->order_id    = 0;
                                    $payLogModel->add_time    = $now;
                                    $payLogModel->update_time = $now;
                                    $payLogModel->save();

                                    //config/type.php    9 => '水果大作战下单'
                                    $key = '9-' . $userId . '-' . $awardGold . '-' . $currentIssue['id'];

                                    //business表  5 => 水果大作战
                                    UserCoinLog::log(5, $userId, UserCoinLog::TYPE_XYB, $awardGold, '水果大作战开奖奖励', $key);
                                    
                                    //给上家奖励 1% 小妖币奖励，最小为0.01
                                    try {
                                        $this->rewardFinder($user, $awardGold);
                                    } catch ( \Exception $e) {
                                        echo "给上级发放奖励错误：" . $e->getMessage() . "\n";
                                    }
                                }
                            } else {
                                echo "没有中奖记录\n";
                            }
                        }
                    }

                    //创建下一期
                    $nextIssueId = Issue::createNextIssue();

                    if (empty($nextIssueId)) {
                        throw new \Exception("开奖后无法创建下一期", 3);
                    }
                    DB::commit();
                    echo "开奖成功\n";
                } catch (\Exception $e) {
                    DB::rollBack();
                    Log::debug($e);
                    echo "开奖失败: ", $e->getMessage(), "\n";
                }
            }
        } catch (\Exception $e) {
            Log::debug($e);
            echo "开奖失败: ", $e->getMessage(), "\n";
        }
        echo "Issue: {$currentIssue['id']} end\n\n";
    }

    /**
     * 奖励上级
     */
    public function rewardFinder($user, $total)
    {
        if ($this->reward_count) {
            if ($finder = User::where('id', $user->finder_id)->first()) {
                if (floatval($xyb = bcmul($total, 0.01, 2))) {
                    if(!$gameZghpt = $finder->game_zghpt){
                        $gameZghpt = new GameZghpt();
                        $gameZghpt->user_id = $finder->id;
                        $gameZghpt->quota = 0;
                        $gameZghpt->level = 0;
                        $gameZghpt->save();
                    }
                    if($gameZghpt->level) {
                        $tmp_xyb = $xyb * 100;
                        $message = '恭喜您获得' . $tmp_xyb . '个小妖币的推荐奖励。';

                        $key = '5-'. $finder->id . '-' . $xyb . '-' . time() . '-1';
                        UserCoinLog::log( 5, $finder->id, UserCoinLog::TYPE_XYB, $xyb, '推荐奖励', $key );
                    } else {
                        $message = '您好，您错过了'. $xyb .'小妖币的红包，请<a href="http://ga.cloudxt.cn/zghpt/vip/page">立即升级VIP</a>！';
                    }

                    try{
                        app('wechat')->staff->message($message)->to($finder->openid)->send();
                    } catch (\Exception $e){
                    }

                    $this->reward_count--;
                    $this->rewardFinder($finder, $total);
                }
            }
        }
    }
}
